"""
日志插件高级使用示例
展示在实际应用场景中如何使用日志插件
"""
import requests
import json
import time
from datetime import datetime, timedelta
import random

BASE_URL = "http://localhost:8000"

class LoggerClient:
    """日志客户端封装类"""
    
    def __init__(self, base_url):
        self.base_url = base_url
    
    def log(self, level, message, source="app", details=None):
        """记录日志"""
        log_data = {
            "level": level,
            "message": message,
            "source": source,
            "details": details
        }
        
        response = requests.post(f"{self.base_url}/logger/log", json=log_data)
        return response.status_code == 200
    
    def get_logs(self, level=None, source=None, limit=100):
        """查询日志"""
        params = {"limit": limit}
        if level:
            params["level"] = level
        if source:
            params["source"] = source
        
        response = requests.get(f"{self.base_url}/logger/logs", params=params)
        if response.status_code == 200:
            return response.json()
        return None
    
    def get_stats(self):
        """获取统计信息"""
        response = requests.get(f"{self.base_url}/logger/stats")
        if response.status_code == 200:
            return response.json()
        return None

def simulate_user_activity(logger):
    """模拟用户活动"""
    print("=== 模拟用户活动 ===")
    
    # 模拟用户登录
    logger.log("INFO", "用户登录", "auth", {
        "user_id": 12345,
        "username": "testuser",
        "ip": "192.168.1.100",
        "user_agent": "Mozilla/5.0..."
    })
    
    # 模拟用户浏览页面
    pages = ["/home", "/products", "/cart", "/checkout"]
    for page in pages:
        logger.log("DEBUG", f"用户访问页面: {page}", "navigation", {
            "user_id": 12345,
            "page": page,
            "session_id": "sess_123456"
        })
        time.sleep(0.1)
    
    # 模拟用户购买
    logger.log("INFO", "用户完成购买", "purchase", {
        "user_id": 12345,
        "order_id": "ord_789",
        "amount": 99.99,
        "items": ["product1", "product2"]
    })
    
    print("✓ 用户活动模拟完成")

def simulate_system_operations(logger):
    """模拟系统操作"""
    print("\n=== 模拟系统操作 ===")
    
    # 模拟数据库操作
    db_operations = [
        ("查询用户信息", "SELECT * FROM users WHERE id = 12345"),
        ("更新用户状态", "UPDATE users SET last_login = NOW()"),
        ("插入订单记录", "INSERT INTO orders (user_id, amount) VALUES (12345, 99.99)")
    ]
    
    for op_name, query in db_operations:
        logger.log("DEBUG", f"数据库操作: {op_name}", "database", {
            "query": query,
            "execution_time": random.uniform(0.01, 0.05),
            "rows_affected": random.randint(1, 10)
        })
        time.sleep(0.05)
    
    # 模拟API调用
    api_calls = [
        ("支付API", "POST /api/payment", 200),
        ("库存API", "GET /api/inventory", 200),
        ("通知API", "POST /api/notification", 500)  # 模拟错误
    ]
    
    for api_name, endpoint, status in api_calls:
        if status == 200:
            logger.log("INFO", f"API调用成功: {api_name}", "api", {
                "endpoint": endpoint,
                "status_code": status,
                "response_time": random.uniform(0.1, 0.5)
            })
        else:
            logger.log("ERROR", f"API调用失败: {api_name}", "api", {
                "endpoint": endpoint,
                "status_code": status,
                "error": "Internal Server Error"
            })
        time.sleep(0.1)
    
    print("✓ 系统操作模拟完成")

def simulate_error_scenarios(logger):
    """模拟错误场景"""
    print("\n=== 模拟错误场景 ===")
    
    # 模拟文件操作错误
    logger.log("ERROR", "文件上传失败", "file_upload", {
        "file_name": "large_file.zip",
        "file_size": "50MB",
        "error": "磁盘空间不足",
        "retry_count": 3
    })
    
    # 模拟网络连接错误
    logger.log("WARNING", "外部服务连接超时", "external_service", {
        "service": "payment_gateway",
        "timeout": 30,
        "retry_count": 2,
        "fallback_used": True
    })
    
    # 模拟权限错误
    logger.log("ERROR", "权限验证失败", "auth", {
        "user_id": 12345,
        "resource": "/admin/users",
        "required_permission": "admin:users:read",
        "user_permissions": ["user:read", "user:write"]
    })
    
    # 模拟系统资源不足
    logger.log("CRITICAL", "内存使用率过高", "system", {
        "memory_usage": "95%",
        "available_memory": "512MB",
        "total_memory": "8GB",
        "action_taken": "重启服务"
    })
    
    print("✓ 错误场景模拟完成")

def analyze_logs(logger):
    """分析日志"""
    print("\n=== 日志分析 ===")
    
    # 获取统计信息
    stats = logger.get_stats()
    if stats:
        print(f"总日志数: {stats['total_logs']}")
        print("\n按级别统计:")
        for level, count in stats['logs_by_level'].items():
            print(f"  {level}: {count}")
        
        print("\n按来源统计:")
        for source, count in stats['logs_by_source'].items():
            print(f"  {source}: {count}")
    
    # 查询错误日志
    error_logs = logger.get_logs(level="ERROR")
    if error_logs and error_logs['logs']:
        print(f"\n错误日志数量: {error_logs['count']}")
        print("最近的错误:")
        for log in error_logs['logs'][:3]:
            print(f"  [{log['timestamp']}] {log['source']}: {log['message']}")
    
    # 查询系统日志
    system_logs = logger.get_logs(source="system")
    if system_logs and system_logs['logs']:
        print(f"\n系统日志数量: {system_logs['count']}")
        print("最近的系统日志:")
        for log in system_logs['logs'][:3]:
            print(f"  [{log['timestamp']}] {log['level']}: {log['message']}")

def export_logs_for_analysis(logger):
    """导出日志用于分析"""
    print("\n=== 导出日志 ===")
    
    # 导出JSON格式
    response = requests.get(f"{BASE_URL}/logger/export?format=json")
    if response.status_code == 200:
        data = response.json()
        print(f"JSON格式导出成功，包含 {data['count']} 条日志")
        
        # 保存到文件
        with open("logs_export.json", "w", encoding="utf-8") as f:
            f.write(data['data'])
        print("✓ 日志已保存到 logs_export.json")
    
    # 导出文本格式
    response = requests.get(f"{BASE_URL}/logger/export?format=text")
    if response.status_code == 200:
        data = response.json()
        print(f"文本格式导出成功，包含 {data['count']} 条日志")
        
        # 保存到文件
        with open("logs_export.txt", "w", encoding="utf-8") as f:
            f.write(data['data'])
        print("✓ 日志已保存到 logs_export.txt")

def demonstrate_log_filtering(logger):
    """演示日志过滤功能"""
    print("\n=== 日志过滤演示 ===")
    
    # 按时间范围查询
    now = datetime.now()
    one_hour_ago = now - timedelta(hours=1)
    
    response = requests.get(f"{BASE_URL}/logger/logs", params={
        "start_time": one_hour_ago.isoformat(),
        "end_time": now.isoformat()
    })
    
    if response.status_code == 200:
        data = response.json()
        print(f"最近1小时的日志: {data['count']} 条")
    
    # 复杂查询：ERROR级别的API日志
    response = requests.get(f"{BASE_URL}/logger/logs", params={
        "level": "ERROR",
        "source": "api"
    })
    
    if response.status_code == 200:
        data = response.json()
        print(f"API错误日志: {data['count']} 条")
    
    # 分页查询
    response = requests.get(f"{BASE_URL}/logger/logs", params={
        "limit": 5,
        "offset": 0
    })
    
    if response.status_code == 200:
        data = response.json()
        print(f"第1页日志 (5条): {data['count']} 条")

def main():
    """主函数"""
    print("=== 日志插件高级使用示例 ===\n")
    
    # 创建日志客户端
    logger = LoggerClient(BASE_URL)
    
    try:
        # 1. 模拟用户活动
        simulate_user_activity(logger)
        
        # 2. 模拟系统操作
        simulate_system_operations(logger)
        
        # 3. 模拟错误场景
        simulate_error_scenarios(logger)
        
        # 4. 分析日志
        analyze_logs(logger)
        
        # 5. 导出日志
        export_logs_for_analysis(logger)
        
        # 6. 演示过滤功能
        demonstrate_log_filtering(logger)
        
        print("\n=== 示例完成 ===")
        print("生成的日志文件:")
        print("- logs_export.json: JSON格式的完整日志")
        print("- logs_export.txt: 文本格式的完整日志")
        
    except requests.exceptions.ConnectionError:
        print("错误: 无法连接到服务器")
        print("请确保FastAPI应用正在运行: python main.py")
    except Exception as e:
        print(f"示例运行过程中发生错误: {e}")

if __name__ == "__main__":
    main() 